import knex, { Knex } from "knex";
import fs from "fs";
import path from "path";
let dbInstance: Knex;
if (!dbInstance) {
  let dbPath;
  if (location.href.startsWith("http")) {
    dbPath = path.join(process.execPath, "../../../../src/common/db.db");
  } else {
    const appDataPath =
      process.env.APPDATA || (process.platform === "darwin" ? process.env.HOME + "/Library/Preferences" : process.env.USERPROFILE + "/.local/share");

    console.log("AppData path:", appDataPath);
    console.log("Process execPath:", process.execPath);

    dbPath = path.join(appDataPath, "electron-vue/db.db");
    let dbIsExist = fs.existsSync(dbPath);
    console.log("Database exists:", dbIsExist);
    console.log("Target DB path:", dbPath);

    if (!dbIsExist) {
      let resourceDbPath = path.join(process.execPath, "../resources/db.db");
      console.log("Resource DB path:", resourceDbPath);

      // 确保目标目录存在
      const dbDir = path.dirname(dbPath);
      if (!fs.existsSync(dbDir)) {
        try {
          fs.mkdirSync(dbDir, { recursive: true });
          console.log("Created directory:", dbDir);
        } catch (err) {
          console.error("Error creating directory:", err);
          throw err;
        }
      }

      // 检查源文件是否存在
      if (!fs.existsSync(resourceDbPath)) {
        console.error("Source database file not found:", resourceDbPath);
        throw new Error("Source database file not found");
      }

      try {
        fs.copyFileSync(resourceDbPath, dbPath);
        console.log("Database file copied successfully");
      } catch (err) {
        console.error("Error copying database file:", err);
        throw err;
      }
    }
  }
  dbInstance = knex({
    client: "better-sqlite3",
    connection: { filename: dbPath },
    useNullAsDefault: true,
  });
}
export let db = dbInstance;
